BUTLD :=../build
SRC :=.

boot = boot.bin
loader = loader.bin
master = master.img

ENTRYPOINT := 0x10000 

# 模式输出
$(BUTLD)/boot/%.bin:$(SRC)/boot/%.asm
	$(shell mkdir  -p $(dir $@))
	nasm -f bin $< -o $@ 

$(BUTLD)/kernel/%.o:$(SRC)/kernel/%.asm
	$(shell mkdir  -p $(dir $@))
	nasm -f elf32 $< -o $@
  
$(BUTLD)/kernel.bin:$(BUTLD)/kernel/start.o
	$(shell mkdir  -p $(dir $@))
	ld -m elf_i386 -static $^ -o $@  -Ttext $(ENTRYPOINT)

# elf 文件在加载的时候需要特殊处理，下面的操作直接从内存中读出来之后放到内存中之后跳过去执行就行了，不用在对elf 文件进行处理
#下面这样处理的话可以跟方便
$(BUTLD)/system.bin : $(BUTLD)/kernel.bin
	objcopy -O binary $< $@

$(BUTLD)/system.map:$(BUTLD)/kernel.bin
	nm $< | sort > $@



$(BUTLD)/$(master):$(BUTLD)/boot/$(boot)	\
	$(BUTLD)/boot/$(loader)					\
	$(BUTLD)/system.bin						\
	$(BUTLD)/system.map
	yes | bximage -q -hd=16 -func=create -sectsize=512 -imgmode=flat $@
	dd if=$(BUTLD)/boot/$(boot) of=$@ bs=512 count=1 conv=notrunc
	dd if=$(BUTLD)/boot/$(loader) of=$@ bs=512 count=4 seek=2 conv=notrunc
	dd if=$(BUTLD)/system.bin of=$@ bs=512 count=200 seek=10 conv=notrunc

test: $(BUTLD)/$(master)


.PHONY : project
project: 
	$(BUTLD)/boot/$(boot)
	$(BUTLD)/boot/$(loader)
	$(BUTLD)/$(master)
	yes | bximage -q -hd=16 -func=create -sectsize=512 -imgmode=flat $(master)
	dd if=$(boot) of=$(master) bs=512 count=1 conv=notrunc
	dd if=$(loader) of=$(master) bs=512 count=4 seek=2 conv=notrunc

.PHONY : USB
USB : $(BUTLD)/boot/$(boot) /dev/sdb
	sudo dd if=/dev/sdb of=tmp.bin bs=512 count=1 conv=notrunc
	cp tmp.bin usb.bin
	sudo rm tmp.bin
	dd if=$(BUTLD)/boot/$(boot) of=usb.bin bs=446 count=1 conv=notrunc
	sudo dd if=usb.bin of=/dev/sdb bs=512 conv=notrunc
	rm usb.bin


.PHONY : clean
clean :
	rm -rf $(BUTLD)

.PHONY : bochs
bochs : $(BUTLD)/$(master)
	bochs -q

